package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    //新增分类方法
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("新增分类成功");
    }
    //分页查询方法
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //分页构造器
        Page<Category> pg = new Page<Category>();
        //条件查询器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<Category>();
        //排序条件-sort排序
        lqw.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(pg, lqw);
        return R.success(pg);
    }
    //删除分类方法
    @DeleteMapping
    public R<String> delete(Long id) {
//        categoryService.removeById(id);
        log.info("删除分类的id为:{}",id);
        categoryService.removeById(id);
        return R.success("分类信息删除成功");
    }
    //修改分类方法
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }
    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        System.out.println(file);
        return R.success(file.getName());
    }
    //菜品分类查询*
    @GetMapping("/list")
    public R<List<Category>> getList(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //查询条件
        lqw.eq(category.getType() != null,Category::getType,category.getType());
        //按照条件排序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        //最后将结果返回
        return R.success(list);
    }
}
